package com.chao.common.codeGeneration.generation;

import com.chao.common.codeGeneration.bean.Table;
import com.chao.common.codeGeneration.generation.CodeConstant;
import com.chao.common.codeGeneration.generation.JdbcDao;
import com.chao.common.codeGeneration.source.*;
import com.chao.common.config.initialize.Initialize;
import com.chao.common.util.exception.SysException;

import java.util.ArrayList;
import java.util.List;

public class Generation{

	public static String author; //作者

	private String db; //需要生成代码的数据表所在库 一次只能生成一个数据库里的表
	private String service; //代码所属服务名 一次只能生成一个服务里的模块

	private String tb; //需要生成代码的数据表名 多个表用,隔开
	private String mode; //模块名 多个,隔开跟包名一一对应
	private String notes; //模块注释 多个,隔开跟包名一一对应
	private String pag; //模块所属包名 多个,隔开跟模块名一一对应 若重复 则代码会放到同一个包里
	private String daima; //设置需要生成哪些代码 多个 ,隔开 跟表名 一一对应

	private String[][] function; //新增的代码功能

	public Generation(String author,String db, String service, String tb, String mode, String pag, String notes,String daima,String[]... function) {
		Generation.author = author;
		this.db = db;
		this.service = service;
		this.tb = tb;
		this.mode = mode;
		this.pag = pag;
		this.notes = notes;
		this.daima = daima;
		this.function = function;

		//开始生成
		start();
	}

	public void start(){
		String[] tbs = tb.split(",");
		String[] modes = mode.split(",");
		String[] pags = pag.split(",");
		String[] notess = notes.split(",");
		String[] daimas = daima.split(",");

		List<Table> tableList = new ArrayList<>();
		JdbcDao jdbc = Initialize.toJdbc();
		if(null == jdbc){
			throw new SysException("数据库连接失败!");
		}
		for (int i = 0; i < tbs.length; i++) {
			Table table = jdbc.findByUsername(db,tbs[i]);
			table.setPacName(pags[i]);
			table.setPojoName(notess[i]);
			table.setPojoKey(modes[i].substring(0, 1).toUpperCase()+modes[i].substring(1));
			table.setUpojoKey(modes[i]);
			table.setDaima(Integer.valueOf(daimas[i]));
			table.setService(service);
			table.setFunction(function[i]);
			tableList.add(table);
		}

		tableList.forEach(this::start);
	}

	public void start(Table table){
		//解析获取当前项目文件路径
		String filePath = Initialize.class.getClassLoader().getResource("").getPath().replace("/target/classes/","");
		String path = filePath + String.format(CodeConstant.SERVICE_PATH,table.getService(),table.getPacName());
		if(table.getDaima() > 0 && table.getDaima() < 4){
			ToBean.toBean(table,path);
		}
		switch (table.getDaima()){
			case 0: DeleteFile.deleteAll(table,filePath);break;
			case 3: ToController.toController(table,path);
			case 2: ToService.toService(table,path);
			case 1: ToDB.toMapper(table,path);
		}
	}

}
